/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define([], function () {

    return {
        update: function (element, valueAccessor, allBindingsAccessor) {
            // a link must be bound to an object of type :
            // { id: ..., label: ..., type: ... }
            var value = ko.unwrap(valueAccessor());

            if (!value) {
                // no object, no link
                $(element).attr('href', null).text('-');
                return;
            }

            value = ko.mapping.toJS(value);

            // what kind of object we're dealing with.. (PersonnePhysique, Message, PoursuiteOrdinaire, ...)
            // if the type property is falsy, try to use an alternate objectType binding
            var objType = value.type || value.kind || allBindingsAccessor().objectType;

            // the links provided by this binding are always routing to 'detail/.....'
            var href = '#/detail/' + objType + '/' + value.id;
            if(objType === 'readFile') {
                href = 'api/readFile/' + value.id;
            }

            if (!value.id || !objType) {
                href = null;
                // prevent click from happening on this link
                // the off() method has to be called on mousedown for it to happen
                // _after_ all possible click event are bound in other modules, but before
                // any of them is executed
                // otherwise some late comer could still rebind click event...
                $(element).addClass('op-disabled-link').mousedown(function(evt) {
                    $(this).off('click');
                    evt.stopPropagation();
                });
            }
            var label = value.label || value.nom;
            $(element).text(label).attr('href', href);
        }
    };
});